from datetime import datetime,timedelta
import requests,json,configparser,os,time
from apscheduler.schedulers.blocking import BlockingScheduler
import weixin
from main import LineName


# def auto():
#     interval = 20
#     top = {}
#     url = 'http://127.0.0.1:8080/data/'
#     end = datetime.now()
#     start = (datetime.now() - timedelta(minutes=interval))
#     # end = '2020-4-13 20:00:00'
#     # start = '2020-4-13 19:00:00'
#     params = {'start':start.strftime("%Y-%m-%d %H:%M:%S"),'end':end.strftime("%Y-%m-%d %H:%M:%S")}
#     r = requests.get(url,params=params)
#     data = r.json()
#     for key,value in data.items():
#         if data[key]['急停次数'] == '没有数据':
#             text = "{0}-{1}，{2}线没有急停数据，请确认终端是否正确上传数据。。。".format(start.strftime("%H:%M"),end.strftime("%H:%M"), key)
#             top.update({key:text})
#         else:
#             top3 = []
#             for k in sorted(data[key]['急停时间'], key=data[key]['急停时间'].__getitem__,reverse=True):
#                 top3.append([k,data[key]['急停时间'][k]])
#             text = '{0}-{1}，{2}线急停次数前三位是：\n{3}：\n按下{4}次，影响时间合计{5}秒\n{6}：\n' \
#                            '按下{7}次，影响时间合计{8}秒\n{9}：\n按下{10}次，影响时间合计{11}秒'\
#                 .format(start.strftime("%H:%M"),end.strftime("%H:%M"),key,top3[0][0], data[key]['急停次数'][top3[0][0]], top3[0][1],
#                                 top3[1][0], data[key]['急停次数'][top3[1][0]], top3[1][1],
#                                 top3[2][0], data[key]['急停次数'][top3[2][0]], top3[2][1])
#             top.update({key:text})
#     weixin.sendweixin(top)

def auto(debug=False):
    interval = 20
    url = 'http://127.0.0.1:8080/data/'
    end = datetime.now()
    start = (datetime.now() - timedelta(minutes=interval))
    params = {'start': start.strftime("%Y-%m-%d %H:%M:%S"), 'end': end.strftime("%Y-%m-%d %H:%M:%S")}
    r = requests.get(url, params=params)
    data = r.json()
    print(data[1])
    weixin.sendweixin(data[1],debug=debug)

def new_auto(debug=False):
    interval = 20
    url = 'http://127.0.0.1:8080/data/'
    end = datetime.now()
    start = (datetime.now() - timedelta(minutes=interval))
    params = {'start': start.strftime("%Y-%m-%d %H:%M:%S"), 'end': end.strftime("%Y-%m-%d %H:%M:%S")}
    r = requests.get(url, params=params)
    data = r.json()
    print(data[1])
    weixin.send(data)



if __name__ == '__main__':
    new_auto()
    # scheduler = BlockingScheduler()
    # # scheduler.add_job(auto_send, 'cron', minute ='0,10,20,30,40,50', args=[interval])
    # scheduler.add_job(auto, 'cron', minute ='0,10,20,30,40,50')
    # scheduler.start()